package com.example.moneygrosService;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.moneygrosService.MainActivityService.DB_TOKEN;
import com.example.moneygrosService.database.MoneyContract.UserProfiles;
import com.example.moneygrosService.database.MoneyContract.UserProfilesColumns;
import com.example.moneygrosService.database.MoneyContract.UsersColumns;
import com.example.moneygrosService.handlers.ModifyUserProfileHandler;


public class UserProfileActivity extends Activity {

	private static final String TAG = "UserProfileActivity";

	private Button modify_user_Button;
	private EditText modify_user_user_id_EditText;
	private EditText modify_user_user_name_EditText;
	private EditText modify_user_user_phone_EditText;
	private EditText modify_user_user_bluetooth_mac_EditText;

	private User mUser;

	public UserProfileActivity() {
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);


		if(mUser==null)
			mUser = new User();
		
		setContentView(R.layout.user_profile_layout);

		//		if (DatabaseService.isRunning()) {
		//			Log.v(TAG, "(DatabaseService.isRunning())");
		//            doBindService();
		//        } else {
		//			Log.v(TAG, "!(DatabaseService.isRunning())");
		//
		//        }

		// Initialisation des tests pour l'ajout d'utilisateur 
		modify_user_user_id_EditText = (EditText)findViewById(R.id.modify_user_user_id);
		modify_user_user_id_EditText.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				EditText eText = (EditText)v;
				String str=eText.getText().toString();
				if(isCorrectMail(str)){
					eText.setTextColor(Color.BLACK);
				} else {
					eText.setTextColor(Color.RED);
				}
			}

			boolean isCorrectMail (String s){		    
				String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
				CharSequence inputStr = s;

				Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
				Matcher matcher = pattern.matcher(inputStr);
				return matcher.matches();
			}
		});

		modify_user_user_name_EditText = (EditText)findViewById(R.id.modify_user_user_name);

		modify_user_user_phone_EditText = (EditText)findViewById(R.id.modify_user_user_phone);
		modify_user_user_phone_EditText.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				EditText eText = (EditText)v;
				String str=eText.getText().toString();
				if(PhoneNumberUtils.isGlobalPhoneNumber(str)){
					eText.setTextColor(Color.BLACK);
				} else {
					eText.setTextColor(Color.RED);
				}
			}
		});
		

		modify_user_user_bluetooth_mac_EditText = (EditText)findViewById(R.id.modify_user_user_bluetooth_mac);
		modify_user_user_bluetooth_mac_EditText.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				EditText eText = (EditText)v;
				String str=eText.getText().toString();
				if(isCorrectBtMAC(str)){
					eText.setTextColor(Color.BLACK);
				} else {
					eText.setTextColor(Color.RED);
				}
			}

			boolean isCorrectBtMAC(String s){		    
//				String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
				String expression = "^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$";
				CharSequence inputStr = s;

				Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
				Matcher matcher = pattern.matcher(inputStr);
				return matcher.matches();
			}
		});


		Button modify_user_Button = (Button) findViewById(R.id.modify_user_modify_button);
		modify_user_Button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// faire une requete à la BDD (demander au service)
				//   				User user = new User();
				EditText user_id = (EditText)findViewById(R.id.modify_user_user_id);
				EditText user_name= (EditText)findViewById(R.id.modify_user_user_name);
				EditText user_phone = (EditText)findViewById(R.id.modify_user_user_phone);
				EditText user_bluetooth= (EditText)findViewById(R.id.modify_user_user_bluetooth_mac);

				Bundle bundle = new Bundle();
				bundle.putString(UsersColumns.USER_ID, user_id.getText().toString());
				bundle.putString(UsersColumns.USER_NAME, user_name.getText().toString());
				bundle.putString(UsersColumns.PHONE_NUMBER, user_phone.getText().toString());

				mUser = new User(user_id.getText().toString(), user_name.getText().toString(), user_phone.getText().toString(), user_bluetooth.getText().toString(), "", 0, false);
				//				Intent intent = new Intent(getApplicationContext(), DatabaseService.class);
				Bundle data = new Bundle();
				//				data.putInt("request_code", REQUEST_CODES.SERVICE_MODIFY_USER_PROFILE);
				data.putParcelable("user", mUser);

				//				sendMsgToService(data, REQUEST_CODES.SERVICE_MODIFY_USER_PROFILE);
				//		        doUnbindService();
//				setResult(RESULT_OK, getIntent().putExtras(bundle));
				
				ModifyUserProfileHandler modifyUserProfileHandler = new ModifyUserProfileHandler(getContentResolver(), mUser);
				modifyUserProfileHandler.modifyUserProfile();
				finish();
			}

		});

		fillFields();
		UserProfileQueryHandler userProfileQueryHandler = new UserProfileQueryHandler(getContentResolver());
		userProfileQueryHandler.fetchUserProfile();

	}

	protected void fillFields(){
		Log.v(TAG, "MODIFY_USER_PROFILE");

		String user_id= mUser.getUser_id();
		String user_name = mUser.getUser_name();
		String user_phone_number= mUser.getPhone_number();
		String user_bluetooth_mac= mUser.getBluetooth_MAC();

		if(user_id!=null){
			modify_user_user_id_EditText.setText(user_id);
		}
		if(user_name!=null){
			modify_user_user_name_EditText.setText(user_name);
		}
		if(user_phone_number!=null){
			modify_user_user_phone_EditText.setText(user_phone_number);
		}
		if(user_bluetooth_mac!=null){
			modify_user_user_bluetooth_mac_EditText.setText(user_bluetooth_mac);
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	
    class UserProfileQueryHandler extends AsyncQueryHandler {
		public UserProfileQueryHandler(ContentResolver cr) {
			super(cr);
			// TODO Auto-generated constructor stub
		}

		/* (non-Javadoc)
		 * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
		 */
		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			// TODO Auto-generated method stub
    		switch(token){
//    			case DB_TOKEN.CHECK_USER_UPDATE_USER_PROFILE:
//    			Log.v(TAG, "CHECK_USER_UPDATE_USER_PROFILE");
			case DB_TOKEN.CHECK_USER_PROFILE_FOR_ACTIVITY:
			Log.v(TAG, "CHECK_USER_PROFILE_FOR_ACTIVITY");
    			if(cursor != null){

    				if(cursor.getCount() != 0){
    					//l'utilisateur existe!
    					cursor.moveToFirst();

    	    			Log.v(TAG, "Utilisateur connu");
    					mUser.setVersion(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.VERSION)));
    					mUser.setUser_id(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.USER_ID)));
    					mUser.setUser_name(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.USER_NAME)));
    					mUser.setPhone_number(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.PHONE_NUMBER)));
    					mUser.setBluetooth_MAC(cursor.getString(cursor.getColumnIndex(UserProfilesColumns.BLUETOOTH_MAC)));
    					fillFields();
    				} else {
    					//l'utilisateur n'existe pas!
    					Log.v(TAG, "Utilisateur inconnu");
    					mUser.setVersion("1.0");
    				}

					cursor.close();
    			}
    				
        		break;
    		}
		}
		
		public void fetchUserProfile(){
	    	String[] projection = {BaseColumns._ID, UserProfilesColumns.USER_ID, UserProfilesColumns.USER_NAME, UserProfilesColumns.PHONE_NUMBER, UserProfilesColumns.BLUETOOTH_MAC, UserProfilesColumns.VERSION};
	    	startQuery(DB_TOKEN.CHECK_USER_PROFILE_FOR_ACTIVITY, null, UserProfiles.CONTENT_URI, projection, null, null, null);
	    	
		}
    }

}
